import 'package:dio/dio.dart';
import 'package:flutter_app/models/BaseResponse.dart';

class NetUtil {
  static const String GET = "get";
  static const String POST = "post";

  static void _request(String url, Function callBack,
      {String method,
      Map<String, String> params,
      Function errorCallback}) async {
    print("HTTP____$method>>>>>$url");
    if (params != null && params.isNotEmpty) {
      print("HTTP____params>>>>>${params.toString()}");
    }

    String errorMsg = "";
    int statusCode;

    try {
      Response<BaseResponse> response;
      if (method == GET) {
        if (params != null && params.isNotEmpty) {
          StringBuffer sb = new StringBuffer("?");
          params.forEach((key, value) {
            sb.write("$key=$value&");
          });
          String paramStr = sb.toString();
          paramStr = paramStr.substring(0, paramStr.length - 1);
          url += paramStr;
        }
        response = await Dio().get(url);
      } else {
        if (params != null && params.isNotEmpty) {
          response = await Dio().post(url, data: params);
        } else {
          response = await Dio().post(url);
        }
      }
      statusCode = response.statusCode;
      if (statusCode < 0) {
        errorMsg = "网络请求错误，状态吗：$statusCode";
        _handError(errorCallback, errorMsg);
        return;
      }
      if (response.data != null && response.data.error) {
        if (response.data.error) {
          _handError(errorCallback, errorMsg);
        } else {
          if (callBack != null) {
            callBack(response.data);
          }
        }
      }
    } catch (exception) {
      _handError(errorCallback, errorMsg);
    }
  }

  static void _handError(Function errorCallback, String errorMsg) {
    if (errorCallback != null) {
      errorCallback(errorMsg);
    }
    print("HTTP____errorMsg>>>>>$errorMsg");
  }
}
